package chapter13.eg5;

import io.netty.util.concurrent.DefaultEventExecutor;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;

public class PromiseApp {

  public static void main(String[] args) {
    EventExecutor executor = new DefaultEventExecutor();
    Promise<Integer> promise = new DefaultPromise<>(executor);
    promise.addListener(new GenericFutureListener<Future<? super Integer>>() {
      @Override
      public void operationComplete(Future<? super Integer> future) throws Exception {
        if (future.isSuccess()) {
          System.out.println("任务结束，结果：" + future.get());
        } else {
          System.out.println("任务失败，异常：" + future.cause());
        }
      }
    }).addListener(new GenericFutureListener<Future<? super Integer>>() {
      @Override
      public void operationComplete(Future<? super Integer> future) throws Exception {
        System.out.println("任务结束，balabala...");
      }
    });

    executor.submit(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          // ignore
        }

        promise.setSuccess(123456);
      }
    });

    try {
      promise.sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}
